<template>
  <div class="box">
    <div class="loginBox">
      <div class="headImage"></div>
      <div class="login">
        <h2 style="margin-left: 20px;color: rgb(169,58,51)">登&nbsp;&nbsp;录</h2>
        <div style="margin-left: 20px">欢迎您的登录~</div>
        <el-input type="text" placeholder="请输入手机号" v-model="loginMessage.username"/><br>
        <el-input type="password" placeholder="请输入密码" v-model="loginMessage.password"/><br>
        <div style="margin-left: 20px">
          <el-button type="danger" link size="small" @click="toRegister">还没有账号？</el-button>
          <el-button type="danger" link size="small" style="margin-left: 122px;" @click="toForget()">忘记密码？</el-button>
        </div>
        <el-button class="loginBt" @click="toLogin">登录</el-button>
      </div>
    </div>
    <el-dialog v-model="dialogVisible1" style="width: 400px;">
      <el-steps style="max-width: 500px;" :active="active" align-center>
        <el-step title="第一步" description="输入注册信息" />
        <el-step title="完成" description="注册结果" />
      </el-steps>
      <div v-if="divVisible1" style="margin-top: 20px;">
        <el-input v-model="registerUser.phone" placeholder="手机号" style="width: 330px;"></el-input>
        <el-input v-model="registerUser.password" placeholder="请输入6~18位密码，同时包含数字和字母" type="password" show-password style="width: 330px;"></el-input>
        <el-input v-model="registerUser.password1" placeholder="确认密码" type="password" show-password style="width: 330px;"></el-input>
      </div>
      <div v-if="divVisible2">
        <el-result v-if="resultTrue" icon="success" title="注册成功！"></el-result>
        <el-result v-else icon="error" title="注册失败，该账号已存在！"></el-result>
      </div>
      <el-button style="margin-top: 12px;margin-left: 140px;--el-button-bg-color: rgb(169,58,51);color: white" @click="next">{{ dialogButton }}</el-button>
    </el-dialog>
    <el-dialog v-model="dialogVisible2" style="width: 400px">
      <el-input v-model="registerUser.phone" placeholder="请输入您的手机号" style="width: 330px;"></el-input>
      <el-input v-model="registerUser.password" placeholder="请输入新的6~18位密码，同时包含数字和字母" type="password" show-password style="width: 330px;"></el-input>
      <el-input v-model="registerUser.password1" placeholder="确认密码" type="password" show-password style="width: 330px;"></el-input>
      <el-button style="margin-top: 12px;margin-left: 130px;--el-button-bg-color: rgb(169,58,51);color: white;width: 100px" @click="sure">确认</el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {Action, ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";
import {userApi} from "../../api/app.js";
import _ from "lodash"

const router = useRouter();

const reg_phone = /^1\d{10}$/; // 手机号正则（1开头11位）
const reg_password = /^(?=.*\d)(?=.*[A-z])[\da-zA-Z]{6,18}$/; // 密码正则（包含数字和字母 6~18位）
// 登录信息
const loginMessage = ref({
  username: '',
  password: '',
});

// 点击登录
const toLogin = _.debounce(() => {
  if(loginMessage.value.username == "" || loginMessage.value.password == "") {
    ElMessageBox.alert('用户名或密码不得为空！','操作失败',{
      confirmButtonText: '确认',
      callback: (action: Action) => {
        ElMessage({
          type: 'error',
          message: '操作失败',
        })
      }
    });
  } else {
    userApi.login({
      customerPhone: loginMessage.value.username,
      customerPassword: loginMessage.value.password
    }).then(response => {
      const user = response[0];
      console.log(user);
      if(response.length != 0) {
        ElMessage({
          message: '登陆成功！',
          type: 'success'
        });
        // 存为全局变量
        localStorage.setItem(
            'user',
            JSON.stringify(user)
        );
        router.push('/main');
      } else {
        ElMessageBox.alert('用户名或密码错误！','操作失败',{
          confirmButtonText: '确认',
          callback: (action: Action) => {
            ElMessage({
              type: 'error',
              message: '操作失败',
            })
          }
        });
      }
    })
  }
}, 500);

// 注册信息
const registerUser = ref({
  phone: '', // 手机号
  password: '', // 密码
  password1: '', // 确认密码
})
const dialogVisible1 = ref(false); // 表单是否可视
const dialogVisible2 = ref(false);
const divVisible1 = ref(false); // 步骤1（输入注册信息）是否可视
const divVisible2 = ref(false); // 步骤2（注册结果）是否可视
const resultTrue = ref(true); // 注册结果 True成功 False失败
const active = ref(0); // 默认步骤从第一个开始
const dialogButton = ref('下一步'); // 表单按钮
// 注册操作
const toRegister = () => {
  dialogVisible1.value = true;
  divVisible1.value = true;
  divVisible2.value = false;
}
// 修改密码
const toForget = () => {
  dialogVisible2.value = true;
}
// 下一步操作
const next = () => {
  if(active.value == 0) { // 当前为第一步，跳转到第二步
    // 有为空的地方
    if(registerUser.value.password === '' || registerUser.value.password1 === '' || registerUser.value.phone === '') {
      ElMessageBox.alert('输入不得为空', '操作失败', {
        confirmButtonText: '确认',
        callback: (action: Action) => {
          ElMessage({
            type: 'error',
            message: `操作失败`,
          })
        },
      })
    } else if(!reg_phone.test(registerUser.value.phone)) { // 手机号不满足格式
      ElMessageBox.alert('手机号输入不符合要求', '操作失败', {
        confirmButtonText: '确认',
        callback: (action: Action) => {
          ElMessage({
            type: 'error',
            message: `操作失败`,
          })
        },
      })
    } else if(!reg_password.test(registerUser.value.password)) { // 密码不满足格式
      ElMessageBox.alert('密码输入不符合要求', '操作失败', {
        confirmButtonText: '确认',
        callback: (action: Action) => {
          ElMessage({
            type: 'error',
            message: `操作失败`,
          })
        },
      })
    } else if(registerUser.value.password !== registerUser.value.password1) { // 两次密码输入不一致
      ElMessageBox.alert('两次密码输入不一致', '操作失败', {
        confirmButtonText: '确认',
        callback: (action: Action) => {
          ElMessage({
            type: 'error',
            message: `操作失败`,
          })
        },
      })
    } else { // 输入全合法
      userApi.register({
          customerPhone: registerUser.value.phone,
          customerPassword: registerUser.value.password
      }).then(response => {
          console.log(response);
          if(response == 1) { // 注册成功
            resultTrue.value = true;
          } else if(response == 0) {
            resultTrue.value = false;
          }
          divVisible1.value = false;
          divVisible2.value = true;
          dialogButton.value = '完成';
          active.value ++;
      }).catch(error => {
          console.log(error);
      })
    }
  } else if(active.value == 1) { // 当前为第二步，关闭弹窗
    dialogVisible1.value = false;
    divVisible2.value = false;
    dialogButton.value = '下一步';
    active.value = 0;
    // 重置数据
    registerUser.value.phone = '';
    registerUser.value.password = '';
    registerUser.value.password1 = '';
  }
}
// 确认修改
const sure = () => {
  userApi.fogetPassword({
    customerId: registerUser.value.phone,
    customerPassword: registerUser.value.password
  }).then(response => {
    console.log(response);
  })
}
</script>

<style scoped>
.box {
  margin: 0;
  padding: 0;
  height: 100vh;
  background: url("../../assets/images/登录背景2.jpg");
  background-size: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.loginBox {
  width: 650px;
  height: 350px;
  border: 1px solid rgb(235,238,239);
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 12px;
  border-top-right-radius: 12px;
  box-shadow: 5px 5px 20px gainsboro;
  display: flex;
  background-color: rgb(169,58,51);
}
.headImage {
  background-image: url("src/assets/images/登录背景3.jpg");
  background-size: 100% 100%;
  width: 350px;
  border-bottom-left-radius: 10px;
  border-top-left-radius: 10px;
}
h3 {
  color: white;
}
.login {
  background-color: white;
  background-size: 100%;
  border-radius: 10px;
  padding-top: 40px;
  flex: 1;
}
.innerBox {
  padding-top: 20px;
  padding-left: 50px;
}
.el-input {
  width: 260px;
  margin-left: 20px;
  margin-top: 30px;
}
.loginBt {
  margin-top: 30px;
  margin-left: 75px;
  width: 150px;
  background-color: rgb(169,58,51);
  color: white;
}
.el-button:hover {
  background-color: rgb(245,108,108);
}
</style>